package com.suntront.module_datasynch

import android.app.Dialog
import android.os.Message
import android.view.View
import androidx.lifecycle.rxLifeScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.mtjsoft.www.kotlinmvputils.base.BaseNotActivity
import com.mtjsoft.www.kotlinmvputils.constants.RouterConstants
import com.mtjsoft.www.kotlinmvputils.imp.AndDialogClickListener
import com.mtjsoft.www.kotlinmvputils.utils.AndDialogUtils
import com.suntront.lib_db.AppDatabase
import com.suntront.module_datasynch.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import okhttp3.internal.wait

/**
 * 数据同步
 * @author mtj
 * @Package com.suntront.module_datasynch.dataasynch
 * @date 2020-05-25 09:56:55
 */
@Route(path = RouterConstants.DataAsynch_index)
class DataAsynchActivity : BaseNotActivity() {
    override fun layoutResId(): Int {
        return R.layout.dataasynch_activity_index
    }

    override fun initView() {
        setPageTitle("数据同步")
    }

    override fun initData() {
    }

    override fun onClick(p0: View) {
        super.onClick(p0)
        when (p0.id) {
            R.id.datasyn_taskdown -> { // 下载抄表任务
                ARouter.getInstance().build(RouterConstants.DataAsynch_Download).navigation()
            }
            R.id.datasyn_update_meter -> { // 上传最新抄表数据
                ARouter.getInstance().build(RouterConstants.DataAsynch_UP).navigation()
            }
            R.id.datasyn_del -> { // 删除上月抄表数据
                AndDialogUtils.builder(getContext())
                    .buildCanCancel(true)
                    .buildCancelClickListener(null)
                    .buildMsg("确认要删除数据吗？")
                    .buildSureClickListener(object : AndDialogClickListener {
                        override fun onClick(paramDialog: Dialog, paramView: View) {
                            paramDialog.dismiss()
                            rxLifeScope.launch({
                                showLoadingUI("正在删除...", false)
                                async {
                                    AppDatabase.getDb().meterDao().deleteAll()
                                    AppDatabase.getDb().userDao().deleteAll()
                                    withContext(Dispatchers.Main) {
                                        toast("删除成功")
                                        hideLoadingUI()
                                    }
                                }
                            }, {
                                toast("删除失败")
                                hideLoadingUI()
                            })
                        }
                    })
                    .buildShowAll(true)
                    .showDialog()
            }
        }
    }

    override fun processHandlerMsg(msg: Message) {
    }

}